<?php

namespace App\Api\Controllers\CustomerApplets;

use App\Models\AliThirdConfig;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\CustomerAppletsUserWechat;
use App\Models\CustomerAppletsUserAlipay;
use App\Models\MerchantStoreAppidSecret;
use Alipayopen\Sdk\AopClient;
use Alipayopen\Sdk\Request\AlipaySystemOauthTokenRequest;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use App\Models\WechatThirdConfig;

class BaseController extends Controller
{
    //第三方开放平台appid
    protected $app_id;
    //第三方开放平台secret
    protected $secret;
    //第三方开放平台token
    protected $token;
    //第三方开放平台aes_key
    protected $aes_key;
    //域名
    protected $domain;
    //微信公众号的appid
    protected $weChatServerAppId;
    //微信公众号的秘钥
    protected $weChatServerSecret;

    // 支付宝第三方参数
    protected $ali_appid; // 最新支付宝小程序的第三方应用的id
    protected $aliPay_applet_template_id; // 支付宝小程序的第三方应用的模板小程序id
    protected $ali_aesKey; // 解密字符串,解密支付宝小程序用户手机号
    protected $rsaPrivateKey; // 支付宝第三方应用的私钥
    protected $rsaPublicKey; // 支付宝第三方应用的公钥

    public function __construct()
    {
        // $this->app_id  = config('api.app_id');
        $model = new WechatThirdConfig();
        $data = $model->getInfo();
        $this->app_id = $data->app_id;
        // $this->secret  = config('api.secret');
        $this->secret  = $data->app_secret;
        $this->token   = $data->token;
        $this->aes_key = $data->aes_key;
        $this->weChatServerAppId   = $data->wechat_server_appid;
        $this->weChatServerSecret  = $data->wechat_server_secret;
        $this->domain  = env('APP_URL');

        // 支付宝第三方参数
        $aliModel = new AliThirdConfig();
        $aliData = $aliModel->getInfo();

        $this->ali_appid = $aliData->aliPay_applet_id;
        $this->aliPay_applet_template_id = $aliData->aliPay_applet_template_id;
        $this->ali_aesKey = $aliData->aes_key;
        $this->rsaPrivateKey = $aliData->rsa_private_key;
        $this->rsaPublicKey = $aliData->rsa_public_key;
    }

    /**
     * 状态码对应的文字描述
     * @param $code
     * @return mixed
     */
    protected function getCodeMessage($code){
        $codeMessage = [
            "200"               => "数据请求成功",
            "202"               => "参数未定义",
            "203"               => "请求方式不正确",
            "404"               => "请求地址不正确",
            "405"               => "用户未在该门店中授权，请先去授权",
            "4001"              => "user_id参数不可为空",
            "4002"              => "store_id参数不可为空",
            "4003"              => "terminal_type参数不可为空",
            "4004"              => "微信appid参数不可为空",
            "4005"              => "微信secret参数不可为空",
            "4006"              => "支付宝appid参数不可为空",
            "4007"              => "支付宝secret参数不可为空",
            "4008"              => "js_code参数不可为空",
            "4009"              => "支付宝认证code不可为空",
            "4010"              => "手机号参数不可为空",
            //以下是微信官方代码code
            "-1"                => "系统繁忙，此时请开发者稍候再试",
            "0"                 => "请求成功",
            "1003"              => "POST参数非法",
            "20002"             => "商品id不存在",
            "40001"             => "获取 access_token 时 AppSecret 错误，或者 access_token 无效",
            "40002"             => "不合法的凭证类型",
            "40003"             => "不合法的 OpenID ，请开发者确认 OpenID （该用户）是否已关注公众号，或是否是其他公众号的 OpenID",
            "40004"             => "不合法的媒体文件类型",
            "40005"             => "上传素材文件格式不对",
            "40006"             => "上传素材文件大小超出限制",
            "40007"             => "不合法的媒体文件 id",
            "40008"             => "不合法的消息类型",
            "40009"             => "图片尺寸太大",
            "40010"             => "不合法的语音文件大小",
            "40011"             => "不合法的视频文件大小",
            "40012"             => "不合法的缩略图文件大小",
            "40013"             => "不合法的appid",
            "40014"             => "不合法的 access_token ，请开发者认真比对 access_token 的有效性（如是否过期），或查看是否正在为恰当的公众号调用接口",
            "40015"              => "不合法的菜单类型",
            "40016"              => "不合法的按钮个数",
            "40017"              => "不合法的按钮类型",
            "40018"              => "不合法的按钮名字长度",
            "40029"              => "无效的 oauth_code",
            "40030"              => "不合法的 refresh_token",
            "40031"              => "不合法的 openid 列表",
            "40032"              => "不合法的 openid 列表长度",
            "40033"              => "不合法的请求字符，不能包含 \uxxxx 格式的字符",
            "40036"              => "不合法的 template_id 长度",
            "40037"              => "不合法的 template_id",
            "40038"              => "不合法的请求格式",
            "40039"              => "不合法的 URL 长度",
            "40097"              => "参数错误",
            "40132"              => "微信号不合法",
            "41001"              => "缺少 access_token 参数",
            "41002"              => "缺少 appid 参数",
            "41003"              => "缺少 refresh_token 参数",
            "41004"              => "缺少 secret 参数",
            "41005"              => "缺少多媒体文件数据，传输素材无视频或图片内容",
            "41006"              => "缺少 media_id 参数",
            "41007"              => "缺少子菜单数据",
            "41033"              => "只允许通过api创建的小程序使用",
            "53300"              => "超出每月次数限制",
            "53301"              => "超出可配置类目总数限制",
            "85001"              => "微信号不存在或微信号设置为不可搜索",
            "85002"              => "小程序绑定的体验者数量达到上限",
            "85003"              => "微信号绑定的小程序体验者达到上限",
            "85004"              => "微信号已经绑定",
            "85005"              => "appid not bind weapp",
            "85006"              => "标签格式错误",
            "85007"              => "页面路径错误",
            "85008"              => "类目填写错误",
            "85009"              => "已经有正在审核的版本",
            "85010"              => "item_list 有项目为空",
            "85011"              => "标题填写错误",
            "85012"              => "无效的审核 id",
            "85013"              => "无效的自定义配置",
            "85014"              => "无效的模板编号",
            "85015"              => "该账号不是小程序账号",
            "85016"              => "域名数量超过限制 ，总数不能超过1000",
            "85017"              => "没有新增域名，请确认小程序已经添加了域名或该域名是否没有在第三方平台添加",
            "85018"              => "域名没有在第三方平台设置",
            "85019"              => "没有审核版本",
            "85020"              => "审核状态未满足发布",
            "85023"              => "审核列表填写的项目数不在 1-5 以内",
            "85043"              => "模板错误",
            "85044"              => "代码包超过大小限制",
            "85045"              => "ext_json 有不存在的路径",
            "85046"              => "tabBar 中缺少 path",
            "85047"              => "pages 字段为空",
            "85048"              => "ext_json 解析失败",
            "85051"              => "version_desc或者preview_info超限",
            "85064"              => "找不到模板",
            "85065"              => "模板库已满",
            "85066"              => "链接错误",
            "85074"              => "小程序未发布, 小程序必须先发布代码才可以发布二维码跳转规则",
            "85077"              => "小程序类目信息失效（类目中含有官方下架的类目，请重新选择类目）",
            "85079"              => "小程序没有线上版本，不能进行灰度",
            "85080"              => "小程序提交的审核未审核通过",
            "85085"              => "小程序提审数量已达本月上限",
            "85086"              => "提交代码审核之前需提前上传代码",
            "86000"              => "不是由第三方代小程序进行调用",
            "86001"              => "不存在第三方的已经提交的代码",
            "86002"              => "小程序还未设置昵称、头像、简介。请先设置完后再重新提交",
            "86007"              => "小程序禁止提交",
            "87011"              => "现网已经在灰度发布，不能进行版本回退",
            "87012"              => "该版本不能回退，可能的原因：1:无上一个线上版用于回退 2:此版本为已回退版本，不能回退 3:此版本为回退功能上线之前的版本，不能回退",
            "87013"              => "撤回次数达到上限（每天一次，每个月 10 次）",
            "80082"              => "没有权限使用该插件",
            "80067"              => "找不到使用的插件",
            "80066"              => "非法的插件版本",
            "9402202"            => "请勿频繁提交，待上一次操作完成后再提交",
            "85094"              => "需提供审核机制说明信息",
            "86009"              => "服务商新增小程序代码提审能力被限制",
            "86010"              => "服务商迭代小程序代码提审能力被限制",
            "91001"              => "不是公众号快速创建的小程序",
            "91002"              => "小程序发布后不可改名",
            "91003"              => "改名状态不合法，小程序发布前可改名的次数为2次，请确认改名次数是否已达上限",
            "91004"              => "昵称不合法",
            "91005"              => "昵称 15 天主体保护",
            "91006"              => "昵称命中微信号",
            "91007"              => "昵称已被占用",
            "91008"              => "昵称命中 7 天侵权保护期",
            "91009"              => "需要提交材料",
            "91010"              => "其他错误",
            "91011"              => "查不到昵称修改审核单信息",
            "91012"              => "其他错误",
            "91013"              => "占用名字过多",
            "91014"              => "+号规则 同一类型关联名主体不一致",
            "91015"              => "原始名不同类型主体不一致",
            "91016"              => "名称占用者 ≥2",
            "91017"              => "+号规则 不同类型关联名主体不一致",
            "53010"              => "名称格式不合法",
            "53011"              => "名称检测命中频率限制",
            "53012"              => "禁止使用该名称",
            "53013"              => "公众号：名称与已有公众号名称重复;小程序：该名称与已有小程序名称重复",
            "53014"              => "公众号：公众号已有{名称 A+}时，需与该帐号相同主体才可申请{名称 A};小程序：小程序已有{名称 A+}时，需与该帐号相同主体才可申请{名称 A}",
            "53015"              => "公众号：该名称与已有小程序名称重复，需与该小程序帐号相同主体才可申请;小程序：该名称与已有公众号名称重复，需与该公众号帐号相同主体才可申请",
            "53016"              => "公众号：该名称与已有多个小程序名称重复，暂不支持申请;小程序：该名称与已有多个公众号名称重复，暂不支持申请",
            "53017"              => "公众号：小程序已有{名称 A+}时，需与该帐号相同主体才可申请{名称 A};小程序：公众号已有{名称 A+}时，需与该帐号相同主体才可申请{名称 A}",
            "53018"              => "名称命中微信号",
            "53019"              => "名称在保护期内",
            "40125"              => "无效的appsecret",
            "45009"              => "接口调用超过限制",
            "47001"              => "解析 JSON/XML 内容错误",
            "48001"              => "api 功能未授权，请确认公众号/小程序已获得该接口，可以在公众平台官网 - 开发者中心页中查看接口权限",
            "42001"              => "access_token 超时，请检查 access_token 的有效期，请参考基础支持 - 获取 access_token 中，对 access_token 的详细机制说明",
            "53202"              => "本月头像修改次数已用完",
            "46001"              => "media_id 不存在",
            "85052"              => "小程序重复发布",
        ];
        if(isset($codeMessage[$code])){
            return $codeMessage[$code];
        }else{
            return null;
        }
    }

    /**
     * 封装定义接口返回的数据格式
     * @param $status 状态码
     * @param $message 状态码对应的文字描述
     * @param string $responseData 返回的数据
     * @return \Illuminate\Http\JsonResponse
     */
    protected function responseDataJson($status,$message = "",$responseData = ""){
        if(!isset($status) || empty($status)){
            return response()->json([]);
        }
        $data['status']    = $status;
        if(!isset($message) || empty($message)){
            $data['message']   = $this->getCodeMessage($status);
        }else{
            $data['message']   = $message;
        }

        if(!empty($responseData)){
            $data['data'] = $responseData;
        }else{
            $data['data'] = "";
        }
        return response()->json($data);
    }

    /**
     * uuid算法
     * @return string
     */
    public function uuid() {
        if (function_exists ( 'com_create_guid' )) {
            return com_create_guid ();
        } else {
            mt_srand ( ( double ) microtime () * 10000 ); //optional for php 4.2.0 and up.随便数播种，4.2.0以后不需要了。
            $charid = strtoupper ( md5 ( uniqid ( rand (), true ) ) ); //根据当前时间（微秒计）生成唯一id.
            $hyphen = chr ( 45 ); // "-"
            $uuid = '' . //chr(123)// "{"
                substr ( $charid, 0, 8 ) . $hyphen . substr ( $charid, 8, 4 ) . $hyphen . substr ( $charid, 12, 4 ) . $hyphen . substr ( $charid, 16, 4 ) . $hyphen . substr ( $charid, 20, 12 );
            //.chr(125);// "}"
            return $uuid;
        }
    }

    /**
     * 根据用户请求的类型去实现不同的数据模型
     * @param $value
     * @return CustomerAppletsUserAlipay|CustomerAppletsUserWechat
     */
    public function weChatOrAliPayRequest($value){
        switch ($value){
            case config("api.weChat"):
                return new CustomerAppletsUserWechat();
                break;
            case config("api.aliPay"):
                return new CustomerAppletsUserAlipay();
                break;
        }
    }

    /**
     * 封装微信请求获取AccessToken方法
     * @param $appid
     * @param $secret
     * @return array|bool|string
     */
    public function getWeChatAccessToken($appid,$secret){
        if(!isset($appid) || empty($appid)){
            return ["status" => 4004 , "message" => $this->getCodeMessage(4004)];
        }
        if(!isset($secret) || empty($secret)){
            return ["status" => 4005 , "message" => $this->getCodeMessage(4005)];
        }

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;

        $result = $this->curl_get_https($url);

        $result_array = json_decode($result,true);

        if(isset($result_array['access_token']) && !empty($result_array['access_token'])){
            $merchantStoreAppIdSecretModel = new MerchantStoreAppidSecret();
            $merchantStoreAppIdSecretModel->updateWeChatInfo($appid,$result_array);
        }

        return $result;
    }

    /**
     * 封装微信请求获取用户openid方法
     * @param $js_code
     * @param $appid
     * @param $secret
     * @return array|bool|string
     */
    public function getWeChatOpenId($js_code,$appid,$secret=''){

        if(!isset($appid) || empty($appid)){
            return ["status" => 4004 , "message" => $this->getCodeMessage(4004)];
        }
        // if(!isset($secret) || empty($secret)){
        //     return ["status" => 4005 , "message" => $this->getCodeMessage(4005)];
        // }
        if(!isset($js_code) || empty($js_code)){
            return ["status" => 4008 , "message" => $this->getCodeMessage(4008)];
        }

        //$url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$js_code."&grant_type=authorization_code";

        $model = new WechatThirdConfig();
        $data = $model->getInfo();
        // $component_appid = config('api.app_id');
        $component_appid = $data->app_id;

        $component_access_token = Cache::get('component_access_token');

        $url = "https://api.weixin.qq.com/sns/component/jscode2session?appid=".$appid."&js_code=".$js_code."&grant_type=authorization_code&component_appid=".$component_appid."&component_access_token=".$component_access_token;

        $result = $this->curl_get_https($url);

        return $result;
    }

    /**
     * 获取支付宝小程序授权信息
     * @param $aliPayAppId
     * @return array
     */
    public function getAuthorizeAppId($aliPayAppId){
        $result = DB::table("customerapplets_authorize_appids")->where(['AuthorizerAppid' => $aliPayAppId])->first();
        if(!empty($result)){
            return ['t_appid' => $result->t_appid,'AuthorizationCode' => $result->AuthorizationCode];
        }else{
            return ['t_appid' => '','AuthorizationCode' => ''];
        }
    }

    /**
     * 封装支付宝请求获取AccessToken方法
     * @param $code
     * @param $aliPayAppId
     * @param $rsaPrivateKey
     * @param $alipayrsaPublicKey
     * @return mixed
     * @throws \Exception
     */
    public function getAliPayOauthToken($code,$aliPayAppId,$rsaPrivateKey,$alipayrsaPublicKey){

        try{
            $authorizeAppId = $this->getAuthorizeAppId($aliPayAppId);
            if(!empty($authorizeAppId['t_appid'])){
                $aliPayAppId = $authorizeAppId['t_appid'];
            }
            $aop = new AopClient();
            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $aliPayAppId;
            $aop->method                = "alipay.system.oauth.token";
            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s",time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';

            $request = new AlipaySystemOauthTokenRequest();
            $request->setGrantType("authorization_code");
            $request->setCode($code);
            if(!empty($authorizeAppId['t_appid'])){
                $result = $aop->execute($request,null,$authorizeAppId['AuthorizationCode']);
            }else{
                $result = $aop->execute($request);
            }

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";

            if(isset($result->$responseNode->access_token) && !empty($result->$responseNode->access_token)){
                $responseData['access_token']   = $result->$responseNode->access_token;
                $responseData['alipay_user_id'] = $result->$responseNode->user_id;
                $responseData['expires_in']     = $result->$responseNode->expires_in;
                $responseData['re_expires_in']  = $result->$responseNode->re_expires_in;
                $responseData['refresh_token']  = $result->$responseNode->refresh_token;
                $responseData['user_id']        = $result->$responseNode->user_id;
                $responseData['status']         = 200;

                $merchantStoreAppIdSecretModel = new MerchantStoreAppidSecret();
                $merchantStoreAppIdSecretModel->updateAliPayInfo($aliPayAppId,$responseData);

            }else{
                $responseData['status']         = 202;
                $responseData['errmsg']         = $result->error_response->sub_msg;
            }

            return $responseData;
        }catch (\Exception $e){
            $responseData['status']         = 202;
            $responseData['errmsg']         = $e->getMessage();
            return $responseData;
        }
    }

    /**
     * xml文件转换
     * @date 2019-05-20
     */
    public function FromXml($xml)
    {
        if(!$xml) {
            echo "xml数据异常！";
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $data;
    }

    /**
     * 解密支付宝小程序用户手机号
     * @param $encryptedData
     * @param $aesKey
     * @return mixed|string
     */
    public function getAliPayMobile($encryptedData,$aesKey){
        //获取手机号解密
        $content = $encryptedData;
        $result  = openssl_decrypt(base64_decode($content), 'AES-128-CBC', base64_decode($aesKey),OPENSSL_RAW_DATA);
        $result  = json_decode($result,true);
        return $result;
    }

    /**
     * 获取第三方平台：
     * 令牌（component_access_token）是第三方平台接口的调用凭据
     * @param $data
     * @return false|string
     */
    public function getComponentAccessToken($data)
    {
        $requestData  = [
            'component_appid'         => $data['component_appid'], //第三方平台 appid
            'component_appsecret'     => $data['component_appsecret'], //第三方平台 appsecret
            'component_verify_ticket' => $data['component_verify_ticket'], //微信后台推送的 ticket
        ];
        try{
            $url    = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
            $result = $this->curl_post_https($url, json_encode($requestData));
            return $result;
        }catch (\Exception $e){
            Log::info("获取微信第三方平台接口调用凭据出错：");
            Log::info($e->getMessage());
        }
    }

    public function parseToken($token = '')
    {
        try {
            JWTAuth::setToken(JWTAuth::getToken());
            $data = JWTAuth::getPayload();//数组
            return (object)$data['sub'];
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * https请求地址，post请求方式
     * @param $url
     * @param $data
     * @return bool|string
     */
    public function curl_post_https($url, $data = "", $header=""){
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        if(!empty($header)){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
            curl_setopt($curl, CURLOPT_HEADER, 0);//返回response头部信息
        }
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        if(!empty($data)){
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            return 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }

    /**
     * https请求地址，get请求方式
     * @param $url
     * @return bool|string
     */
    public function curl_get_https($url,$header = ""){
        $curl = curl_init(); // 启动一个CURL会话

        if(!empty($header)){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        }

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);

//        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36');

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        //curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }


    /**
     * curl请求，get模式
     * @param $url
     * @param string $header
     * @return mixed|string
     */
    public function curl_get($url, $header = "")
    {
        $handle = curl_init();

        if(!empty($header)){
            curl_setopt($handle, CURLOPT_HTTPHEADER, $header);
            curl_setopt($handle, CURLOPT_HEADER, 0); //返回response头部信息
        }

        curl_setopt($handle, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); //模拟用户使用的浏览器
        curl_setopt($handle, CURLOPT_FOLLOWLOCATION, 1); //使用自动跳转
        curl_setopt($handle, CURLOPT_AUTOREFERER, 1); //自动设置Referer
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);// 获取的信息以文件流的形式返回
        curl_setopt($handle, CURLOPT_HEADER, 0);
        curl_setopt($handle, CURLOPT_NOBODY, 0);
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($handle, CURLOPT_URL, $url);
        curl_setopt($handle, CURLOPT_TIMEOUT, 30); //设置超时限制防止死循环
        $tmpInfo = curl_exec($handle); //执行操作
        if (curl_errno($handle)) {
            return 'Errno'.curl_error($handle); //捕抓异常
        }
        curl_close($handle); //关闭CURL会话
        return $tmpInfo; //返回数据,json格式
    }

    /**
     * 校验必填字段
     */
    public function check_required($check, $data)
    {
        $rules = [];
        $attributes = [];
        foreach ($data as $k => $v) {
            $rules[$k] = 'required';
            $attributes[$k] = $v;
        }
        $messages = [
            'required' => ':attribute不能为空',
        ];
        $validator = Validator::make($check, $rules,
            $messages, $attributes);
        $message = $validator->getMessageBag();
        return $message->first();
    }

    /**
     * 统一接口返回格式
     */
    public function sys_response($code = 0, $msg = '', $data = '')
    {
        // 如果$msg为空自动获取
        if (empty($msg)) {
            $key = 'CODE_' . $code;
            $reflectionClass = new \ReflectionClass('\App\Common\Enum\BaseStatusCodeEnum');
            if ($reflectionClass->hasConstant($key)) {
                $msg = $reflectionClass->getConstant($key);
            }
        }

        $returnData = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];
        if ($data === false) {
            unset($returnData['data']);
        }
        return $returnData;
    }

}
